package com.woniuxy.ticketgateway;/*
@author houguai
@create 2021-03-04 16:42
*/



import com.fasterxml.jackson.core.JsonProcessingException;
import com.woniuxy.ticketcommon.ResponceResult;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    //引入openFeigin
    @Autowired
    private AuthService authService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //拦截url
        String url = exchange.getRequest().getURI().getPath();
        //提取jwt
        String jwt = exchange.getRequest().getHeaders().getFirst("jwt");
        //将url和jwt发送给认证中心
        ResponceResult<Void> responceResult=authService.parseJwt(jwt,url);
        if (responceResult.getCode()==403){
            return authErro(exchange.getResponse(),"");
        }else if (responceResult.getCode()==405){
            return authErro(exchange.getResponse(),"");
        }else{

            return chain.filter(exchange);
        }

    }

    /**
     * 认证错误输出
     * @param resp 响应对象
     * @param mess 错误信息
     * @return
     */
    private Mono<Void> authErro(ServerHttpResponse resp, String mess) {
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        resp.getHeaders().add("Content-Type","application/json;charset=UTF-8");

        DataBuffer buffer = resp.bufferFactory().wrap("error".getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }


    @Override
    public int getOrder() {
        return -100;
    }
}











